/***
 * Author: Andrey Zhmaylik
 * 		   Erez Bar
 * 
 * What: Opens file list that recieved from server
 * 		 and displays the selected picures by request.
 */

package house.keepper;

import java.io.IOException;
import java.io.OptionalDataException;

import android.app.ListActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class FileBrowser extends ListActivity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		String m_txt[] = null;
		try {
			m_txt = (String[])Connection.s_in.readObject();
		} catch (OptionalDataException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		setListAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, m_txt) {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				String message = getItem(position);
				TextView resultView = null;
				if (null == convertView || !(convertView instanceof TextView)) {
					resultView = new TextView(super.getContext());
				}
				resultView.setText(message);
				return resultView;
			}

		});
	}
	@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        String f_name = (String)l.getItemAtPosition(position);
        byte file_buf[] = null;
        try {
        	Connection.s_out.writeInt(ServerCommands.DownloadFile.value());
        	Connection.s_out.writeUTF(f_name);
        	if(Connection.s_in.readInt() == ServerCommands.FileIsOk.value())
        	{
				ImageView i = new ImageView(this);
				try {
				
					file_buf = (byte[])Connection.s_in.readObject();
					
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				Bitmap bm = BitmapFactory.decodeByteArray(file_buf, 0, file_buf.length);
				i.setImageBitmap(bm);
				android.app.Dialog picWindow = new android.app.Dialog(this);
	    		picWindow.setTitle(f_name);
	    		picWindow.setContentView(i);
	    		picWindow.show();
        	}
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

}
